import _ from 'lodash-es';
import { timeOutPattern, heightPattern } from './advertiseConfiguration';

/**
 * promise 化，这里会将 success, fail 直接抹掉
 */
const wrapCallbackInvoke = (invoke, defaultValue = {}) => {
  return (options = {}) =>
    new Promise((resolve, reject) => {
      invoke({
        ...defaultValue,
        ...options,
        success: (res) => resolve(res),
        fail: (res) => reject(res),
      });
    });
};

const setStorage = wrapCallbackInvoke(my.setStorage);
export const setLocalStore = (key) => setStorage({ key });

const getStorage = wrapCallbackInvoke(my.getStorage);
export const getLocalStore = (key) => getStorage({ key });

const getAdvertiseHeight = (adContent) => {
  const height = _.last(adContent.match(heightPattern));
  return parseInt(height, 10);
};

const getAdvertiseTimeout = (adContent) => {
  const timeout = _.last(adContent.match(timeOutPattern));
  return parseInt(timeout, 10) / 1000;
};

const getImageAdvertiseInfo = (advertiseContent) => {
  const imgs = advertiseContent.match(/<img.*?>/g);
  const pictureGroup = [];
  let pictures = [];
  imgs.forEach((ele) => {
    const params = ele.split(' ');
    const pic = {};
    params.forEach((attr) => {
      if (attr.indexOf('=') === -1) {
        return;
      }
      const partials = _.slice(attr.match(/(.*?)="(.*?)"/), 1);
      pic[partials[0]] = _.replace(partials[1], /&amp;/g, '&');
    });
    if (_.isEmpty(pic)) {
      return;
    }
    pictures.push(pic);
    if (pic.wrap) {
      pictureGroup.push(pictures);
      pictures = [];
    }
  });
  if (!_.isEmpty(pictures)) {
    pictureGroup.push(pictures);
  }
  const height = getAdvertiseHeight(advertiseContent);
  const timeout = getAdvertiseTimeout(advertiseContent);
  return { pictureGroup, height, timeout };
};

export default {
  setLocalStore,
  getLocalStore,
  getImageAdvertiseInfo,
  getAdvertiseTimeout,
};
